package chapter05_string;

/**
 * 描述：去掉字符串中的k个0
 *
 * @author hl
 * @date 2021/8/8 9:56
 */
public class RemoveKZeros {
    public static void main(String[] args) {
        RemoveKZeros main = new RemoveKZeros();
        String str = "A0000B000";
        String res1 = main.removeKZeros(str, 3);
        String res2 = main.removeKZeros2(str, 3);
        System.out.println(res1);
        System.out.println(res2);
    }
    public String removeKZeros(String str, int k){
        if (str == null || k > str.length() || k < 1) {
            return str;
        }
        String zeros = "";
        String res = "";
        char ch;
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);
            if (ch != '0') {
                if (zeros.length() != k) {
                    res += zeros;
                }
                res += ch;
                zeros = "";
            }else{
                zeros += ch;
            }
        }
        if (zeros.length() != k) {
            res += zeros;
        }
        return res;
    }

    public String removeKZeros2(String str, int k){
        if (str == null || k < 1 || k > str.length()) {
            return str;
        }
        char[] chars = str.toCharArray();
        int count = 0;
        int start = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '0') {
                count++;
                start = start == -1 ? i : start;
            }else{
                if(count == k){
                    while (count-- != 0) {
                        //ASCII码中0表示空
                        chars[start++] = 0;
                    }
                }
                count = 0;
                start = -1;
            }
        }
        if(count == k){
            while (count-- != 0) {
                chars[start++] = 0;
            }
        }
        return String.valueOf(chars);
    }

}
